<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { chessGameService, ChessPieceType, ChessCamp } from '../services/ChessGameService';
import { userService } from '../services/UserService';

// 棋盘基础尺寸
const boardWidth = ref(400);
const boardHeight = computed(() => boardWidth.value * (10 / 9)); // 保持9:10的比例

// 分离的尺寸变量 - 可独立调整
const boardCellSize = ref(50); // 棋盘线间距
const pieceCellSize = ref(49.5); // 棋子尺寸基准

// 计算单元格尺寸，确保棋盘完整显示
watch(boardWidth, () => {
  const cell = boardWidth.value / 8; // 9列需要8个间隔
  boardCellSize.value = cell;
  pieceCellSize.value = cell * 0.85; // 棋子默认占棋盘格的85%，可自行调整
});

// 选中的棋子
const selectedPiece = ref(null);

// 计算棋盘位置
const boardPosition = ref({ x: 0, y: 0 });

// 当前玩家是否可以行动
const canMove = computed(() => {
  return chessGameService.status.value === 'playing' && 
         chessGameService.room.currentTurn === userService.userId.value;
});

// 棋盘是否需要翻转 (黑方视角)
const shouldFlipBoard = computed(() => {
  return chessGameService.myCamp.value === ChessCamp.BLACK;
});

// 获取棋子在棋盘上的像素位置 - 使用pieceCellSize
const getPiecePosition = (row, col) => {
  const cell = pieceCellSize.value;
  if (shouldFlipBoard.value) {
    return {
      x: (8 - col) * cell,
      y: (9 - row) * cell
    };
  } else {
    return {
      x: col * cell,
      y: row * cell
    };
  }
};

// 将屏幕坐标转换为棋盘坐标 - 使用boardCellSize
const screenToBoard = (x, y) => {
  const cell = boardCellSize.value;
  const col = Math.round(x / cell);
  const row = Math.round(y / cell);
  
  if (shouldFlipBoard.value) {
    return {
      row: 9 - row,
      col: 8 - col
    };
  } else {
    return { row, col };
  }
};

// 获取棋子名称
const getPieceName = (pieceType) => {
  switch (pieceType) {
    case ChessPieceType.RED_KING: return '帅';
    case ChessPieceType.RED_ADVISOR: return '仕';
    case ChessPieceType.RED_ELEPHANT: return '相';
    case ChessPieceType.RED_HORSE: return '马';
    case ChessPieceType.RED_CHARIOT: return '车';
    case ChessPieceType.RED_CANNON: return '炮';
    case ChessPieceType.RED_PAWN: return '兵';
    case ChessPieceType.BLACK_KING: return '将';
    case ChessPieceType.BLACK_ADVISOR: return '士';
    case ChessPieceType.BLACK_ELEPHANT: return '象';
    case ChessPieceType.BLACK_HORSE: return '马';
    case ChessPieceType.BLACK_CHARIOT: return '车';
    case ChessPieceType.BLACK_CANNON: return '炮';
    case ChessPieceType.BLACK_PAWN: return '卒';
    default: return '';
  }
};

// 获取棋子颜色
const getPieceColor = (pieceType) => {
  if (pieceType >= ChessPieceType.RED_KING && pieceType <= ChessPieceType.RED_PAWN) {
    return 'red';
  } else if (pieceType >= ChessPieceType.BLACK_KING && pieceType <= ChessPieceType.BLACK_PAWN) {
    return 'black';
  }
  return '';
};

// 棋盘点击事件
const handleBoardClick = (event) => {
  if (!canMove.value) return;
  
  const rect = event.currentTarget.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  
  const boardPos = screenToBoard(x, y);
  const row = boardPos.row;
  const col = boardPos.col;
  
  if (row < 0 || row >= 10 || col < 0 || col >= 9) return;
  
  if (selectedPiece.value) {
    const { row: fromRow, col: fromCol } = selectedPiece.value;
    if (fromRow === row && fromCol === col) {
      selectedPiece.value = null;
      return;
    }
    const success = chessGameService.movePiece(fromRow, fromCol, row, col);
    selectedPiece.value = null;
    return;
  }
  
  const piece = chessGameService.board.value[row][col];
  if (piece === ChessPieceType.EMPTY) return;
  
  // 避免变量重复声明，使用唯一变量名
  const isRedChess = piece >= ChessPieceType.RED_KING && piece <= ChessPieceType.RED_PAWN;
  const isBlackChess = piece >= ChessPieceType.BLACK_KING && piece <= ChessPieceType.BLACK_PAWN;
  
  if ((chessGameService.myCamp.value === ChessCamp.RED && isRedChess) ||
      (chessGameService.myCamp.value === ChessCamp.BLACK && isBlackChess)) {
    selectedPiece.value = { row, col };
  }
};

// 获取棋盘背景
const getBoardBackground = () => {
  return {
    width: `${boardWidth.value}px`,
    height: `${boardHeight.value}px`,
    backgroundColor: '#E8C192',
    position: 'relative'
  };
};

// 绘制棋盘线条 - 使用boardCellSize
const drawBoard = () => {
  const canvas = document.getElementById('chess-board-canvas');
  if (!canvas) return;
  
  const ctx = canvas.getContext('2d');
  const width = boardWidth.value;
  const height = boardHeight.value;
  const cell = boardCellSize.value;
  
  canvas.width = width;
  canvas.height = height;
  ctx.clearRect(0, 0, width, height);
  
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 1;
  
  // 绘制横线 (10条)
  for (let i = 0; i < 10; i++) {
    ctx.beginPath();
    ctx.moveTo(0, i * cell);
    ctx.lineTo(8 * cell, i * cell);
    ctx.stroke();
  }
  
  // 绘制竖线 (9条)
  for (let i = 0; i < 9; i++) {
    ctx.beginPath();
    ctx.moveTo(i * cell, 0);
    ctx.lineTo(i * cell, 9 * cell);
    ctx.stroke();
  }
  
  // 绘制九宫格
  const drawDiagonal = (x1, y1, x2, y2) => {
    ctx.beginPath();
    ctx.moveTo(x1 * cell, y1 * cell);
    ctx.lineTo(x2 * cell, y2 * cell);
    ctx.stroke();
  };
  
  // 上方九宫格
  drawDiagonal(3, 0, 5, 2);
  drawDiagonal(5, 0, 3, 2);
  
  // 下方九宫格
  drawDiagonal(3, 7, 5, 9);
  drawDiagonal(5, 7, 3, 9);
  
  // 绘制兵位和炮位标记
  const drawPositionMark = (x, y) => {
    if (x < 0 || y < 0 || x >= 9 || y >= 10) return;
    
    const size = cell * 0.1;
    const offset = cell * 0.06;
    ctx.lineWidth = 0.8;
    
    // 四个角标记
    ctx.beginPath();
    ctx.moveTo(x * cell - offset, y * cell - size);
    ctx.lineTo(x * cell - offset, y * cell - offset);
    ctx.lineTo(x * cell - size, y * cell - offset);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(x * cell + offset, y * cell - size);
    ctx.lineTo(x * cell + offset, y * cell - offset);
    ctx.lineTo(x * cell + size, y * cell - offset);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(x * cell - offset, y * cell + size);
    ctx.lineTo(x * cell - offset, y * cell + offset);
    ctx.lineTo(x * cell - size, y * cell + offset);
    ctx.stroke();
    
    ctx.beginPath();
    ctx.moveTo(x * cell + offset, y * cell + size);
    ctx.lineTo(x * cell + offset, y * cell + offset);
    ctx.lineTo(x * cell + size, y * cell + offset);
    ctx.stroke();
    
    ctx.lineWidth = 1;
  };
  
  // 炮位标记
  drawPositionMark(1, 2);
  drawPositionMark(7, 2);
  drawPositionMark(1, 7);
  drawPositionMark(7, 7);
  
  // 兵位标记
  drawPositionMark(0, 3);
  drawPositionMark(2, 3);
  drawPositionMark(4, 3);
  drawPositionMark(6, 3);
  drawPositionMark(8, 3);
  
  drawPositionMark(0, 6);
  drawPositionMark(2, 6);
  drawPositionMark(4, 6);
  drawPositionMark(6, 6);
  drawPositionMark(8, 6);
  
  // 楚河汉界
  ctx.font = `${cell * 0.55}px Arial`;
  ctx.fillStyle = '#000';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  
  if (shouldFlipBoard.value) {
    ctx.fillText('楚', 2 * cell, 4.5 * cell);
    ctx.fillText('河', 3 * cell, 4.5 * cell);
    ctx.fillText('汉', 5 * cell, 4.5 * cell);
    ctx.fillText('界', 6 * cell, 4.5 * cell);
  } else {
    ctx.fillText('楚', 2 * cell, 4.5 * cell);
    ctx.fillText('河', 3 * cell, 4.5 * cell);
    ctx.fillText('汉', 5 * cell, 4.5 * cell);
    ctx.fillText('界', 6 * cell, 4.5 * cell);
  }
};

// 初始化棋盘
const initializeBoard = () => {
  drawBoard();
};

// 组件挂载时更新棋盘位置
onMounted(() => {
  const boardElement = document.getElementById('chess-board');
  if (boardElement) {
    const rect = boardElement.getBoundingClientRect();
    boardPosition.value = {
      x: rect.left,
      y: rect.top
    };
  }
  
  window.addEventListener('resize', updateBoardSize);
  initializeBoard();
  
  // 监听尺寸变化
  watch([boardCellSize, pieceCellSize], initializeBoard);
});

// 更新棋盘大小
const updateBoardSize = () => {
  const container = document.querySelector('.chess-board-container');
  if (container) {
    const containerWidth = container.clientWidth;
    boardWidth.value = Math.min(450, containerWidth - 20);
  }
};
</script>

<template>
  <div class="chess-board-container">
    <div 
      id="chess-board"
      class="chess-board"
      :style="getBoardBackground()"
      @click="handleBoardClick"
    >
      <canvas id="chess-board-canvas" class="chess-board-canvas"></canvas>
      
      <!-- 棋子 - 使用pieceCellSize -->
      <div 
        v-for="(row, rowIndex) in chessGameService.board.value" 
        :key="`row-${rowIndex}`"
        class="chess-row"
      >
        <div 
          v-for="(piece, colIndex) in row" 
          :key="`cell-${rowIndex}-${colIndex}`"
          class="chess-piece-container"
          v-if="piece !== ChessPieceType.EMPTY"
          :style="{
            left: `${(shouldFlipBoard ? (8 - colIndex) : colIndex) * pieceCellSize}px`,
            top: `${(shouldFlipBoard ? (9 - rowIndex) : rowIndex) * pieceCellSize}px`,
            transform: 'translate(-50%, -50%)',
            zIndex: 2
          }"
        >
          <div 
            class="chess-piece"
            :class="[
              getPieceColor(piece),
              { selected: selectedPiece && selectedPiece.row === rowIndex && selectedPiece.col === colIndex }
            ]"
            :style="{
              width: `${pieceCellSize}px`,
              height: `${pieceCellSize}px`,
              fontSize: `${pieceCellSize * 0.6}px`,
              lineHeight: `${pieceCellSize}px`
            }"
          >
            {{ getPieceName(piece) }}
          </div>
        </div>
      </div>
      
      <div v-if="chessGameService.status.value === 'game_over'" class="game-over-overlay">
        <div class="game-over-message">游戏结束</div>
      </div>
    </div>
    
    <div class="turn-indicator" v-if="chessGameService.status.value === 'playing'">
      <div class="turn-label">当前回合:</div>
      <div 
        class="turn-value"
        :class="{ 
          'my-turn': chessGameService.room.currentTurn === userService.userId.value,
          'opponent-turn': chessGameService.room.currentTurn !== userService.userId.value
        }"
      >
        {{ chessGameService.room.currentTurn === userService.userId.value ? '我方' : '对方' }}
      </div>
      <div class="timer" v-if="chessGameService.status.value === 'playing'">
        {{ chessGameService.turnTimer.value }}秒
      </div>
    </div>
  </div>
</template>

<style scoped>
.chess-board-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 20px 0;
}

.chess-board {
  border: 2px solid #8B4513;
  background-color: #E8C192;
  position: relative;
  margin: 0 auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  border-radius: 4px;
}

.chess-board-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.chess-row {
  position: relative;
}

.chess-piece-container {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chess-piece {
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  transition: all 0.2s ease;
  border-width: 1px;
  user-select: none;
  cursor: pointer;
}

.chess-piece.red {
  background-color: #f9e4e4;
  color: #c00;
  border-color: #c00;
}

.chess-piece.black {
  background-color: #f8f8f8;
  color: #000;
  border-color: #333;
}

.chess-piece.selected {
  transform: scale(1.1);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.25);
  background-color: #ffffcc;
  z-index: 3;
}

.game-over-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.game-over-message {
  background-color: rgba(255, 255, 255, 0.9);
  padding: 20px 40px;
  border-radius: 10px;
  font-size: 24px;
  font-weight: bold;
  color: #c00;
}

.turn-indicator {
  display: flex;
  align-items: center;
  margin-top: 30px;
  background-color: #f5f5f5;
  padding: 8px 15px;
  border-radius: 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.turn-label {
  margin-right: 10px;
  font-weight: bold;
}

.turn-value {
  font-weight: bold;
}

.my-turn {
  color: #2ecc71;
}

.opponent-turn {
  color: #e74c3c;
}

.timer {
  margin-left: 15px;
  background-color: #333;
  color: white;
  padding: 3px 8px;
  border-radius: 10px;
  font-size: 14px;
}
</style>